$(function(){
	var _id = parseInt($_GET['id']?$_GET['id']: 0);
	
	var global_product = {
			'page': $_GET['page'] ? $_GET['page'] : undefined,//页码
			'pageSize' : $_GET['pageSize'] ? $_GET['pageSize'] : undefined, //页数
			'name': undefined,//商品名称
	};
	var global_remove = [];
	var global_count = 1;
	var goods_count = 1;
	$('#pname').focus();
	
	var product_remove = [];

	dateSelFun($('#produced_time'));
	dateSelFun($('#quality_time'));
	
	setTimeout(function(){ $('#unit').change(); }, 500);
	
	var editor ='';
	    KindEditor.ready(function(K) {
	         editor = K.create('textarea[name="content"]', {
	            cssPath : '../statics/KEditor/plugins/code/prettify.css',
	            uploadJson : '../statics/upload_json.php',
	            fileManagerJson : '../statics/file_manager_json.php',
	            allowFileManager : true,
	            allowImageRemote:false,
	            showRemote : false,
	            afterBlur : function() {
	                this.sync();
	            }
	        });
	    K('#SmallImage').click(function() {
            editor.loadPlugin('image', function() {
                editor.plugin.imageDialog({
                    imageUrl : K('#SmallPic').val(),
                    clickFn : function(url, title, width, height, border, align) {
                        K('#SmallPic').val(url);
                        editor.hideDialog();
                    }
                });
            });
        });
        K('#BigImage').click(function() {
            editor.loadPlugin('image', function() {
                editor.plugin.imageDialog({
                    imageUrl : K('#thumb').val(),
                    clickFn : function(url, title, width, height, border, align) {
                        K('#thumb').val(url);
                        editor.hideDialog();
                    }
                });
            });
        });
        K('#J_selectImage').click(function() {
            editor.loadPlugin('multiimage', function() {
                var aVal="";
                editor.plugin.multiImageDialog({
                    clickFn : function(urlList) {
                        var div = K('#pics');
                        aVal=div.val();
                        K.each(urlList, function(i, data) {
                            if (div.val() == "")
                                aVal =aVal + data.url;
                            else
                                aVal =aVal + "," +  data.url;

                            div.val(aVal);
                        });
                        editor.hideDialog();
                    }
                });
            });
        });
	 });
	 //保存
	$('#saveProduct').on('click', function() {
		var pname = trim($('#pname').val());
		if(!pname){
			$('#pname').next().text('请输入商品名称');
			return false;
		} else{
			$('#pname').next().text('');
		}
		
		var catid = trim($('#catid').val());
		if(!+catid){
			$('#catid').next().text('请选择商品类目');
			return false;
		} else {
			$('#catid').next().text('');
		}
		var supplier = trim($('#supplier').val());
		if(!+supplier){
			$('#supplier').next().text('请选择供应商');
			return false;
		} else {
			$('#supplier').next().text('');
		}
		var unit = trim($('#unit').val());
		if(!+unit){
			$('#unit').next().text('请选择单位');
			return false;
		} else {
			$('#unit').next().text('');
		}
		var warehouse = trim($('#warehouse').val());
		if(!+warehouse){
			$('#warehouse').next().text('仓库需选择一个默认的仓库');
			return false;
		} else {
			$('#warehouse').next().text('');
		}
		
		editor.sync();
		var description = $('#description').val();
		
		var thumb = $('#thumb').val();
		var pics = $('#pics').val();
		var product_id = $(this).attr('data-id');
		var price = $('#price').val();
		
//		editor.html('<h1>232323232<h1>');
		var productInfo = {
			'product_name':pname,
			'category_id' : catid,
			'supplier_id': supplier,
			'quantity_unit':unit,
			'warehouse_id':warehouse,
			'description': description,
			'product_img':thumb,
			'warn_quantity':$('#warnquan').val(),
			'pics' :pics,
			'price':price,
			'supply_price':$('#supply_price').val(),
			'guide_price' :$('#guide_price').val(),
			'product_id': product_id,
			'barcode': $('#barcode').val(),
			'produced_time' : $('#produced_time').val(),
			'quality_time'  : $('#quality_time').val(),
			'sync_shop' : $('#sync_shop').is(':checked') ? 1 : 0,
			'sync_store' : $('#sync_store').is(':checked') ? 1 : 0,
			'accounting_method' : $('#account_method').val(),
		};
		$.post('save-product',productInfo,function(data,status){
			if(status =='success'){
				if(data.Ack =='Success'){
					alertTips('success','保存成功');
					setTimeout(function(){
						window.location.reload();
					},1000);
				} else if(data.Error =='remove the left quantity'){
					alertTips('warning','该仓库还有库存，请先清理库存在处理单位,请慎重处理！');
					return false;
				}else{
					alertTips('error','保存不成功');
					return false;
				}
			} else {
				alertTips('error','网络错误');
			}
		});
		
	});    
	
	////////////////保存辅助单位
	/**
	 * @desc 单位
	 * 
	 */
	(function(){
		select_units = '<select class="units form-control" style="height: 30px;width:80%;float:left;padding:1px;"><option value="0">请选择单位..</option>';
		var ii = layer.load();
		$.get('/instore/list-units', function(data, status){
			layer.close(ii);
			if(status =='success' && data.Ack =='Success'){
				var U = data.Body;
				for(var i in U){
					select_units +='<option value="'+U[i].unit_id+'">'+U[i].unit_name+'</option>';
				}
			}
			select_units +='</select>';
			if(_id != 0){
				//编辑
				initProductUnit();
			}
		});
	
	})();
	
	//返回到上一页
	$('#backUrl').on('click',function(){
		window.history.go(-1);
	})
	/**
	 * @初始化页面
	 */
	function initProductUnit() {
		$.get('get-product-unit-info', {'id' : _id}, function(data, status) {
			if(status =='success' && data.Ack =='Success'){
				var D = data.Body;
				if(D){
					$('#productUnitList').find('tr').remove();
					for(var i in D){
						$('<tr>'
							+'<td class="text-center" name="ids" data-id="'+D[i].product_unit_id+'">'+(+i+1)+'</td>'
							+'<td class="text-center"><a href="javascript:void(0)"class="stock-minus-tr" data-id=""> <i class="fa fa-minus-circle fa-lg" style="color: red;margin-top:10px;"></i></a></td>'
							+'<td class="text-center" name="unit_type" data-id="'+D[i].unit_type+'">'+(+D[i].unit_type?'辅助单位':'基本单位')+'</td>'
							+'<td class="text-center" name="name" data-id="" data-type="'+D[i].unit_type+'">'+select_units
							+'<a class="add-btn add-unit" title="新增" style="float:left;margin:8px 10px 10px 10px;"'
							+'href="javascript:void(0)"><i class="fa fa-plus-circle fa-lg"></i></a></td>'
							+'<td class="text-center" name="rate"><input type="text" class="rate stock-input" value="'+D[i].rate+'"></td>'
							+'<td class="text-center" name="format"><input type="text" class="format stock-input" value="'+D[i].format+'"></td>'
							+'<td class="text-center" name="remark"><input type="text" style="width:100%;" class="remark stock-input" value="'+D[i].remark+'"></td>'
						   +'</tr>').appendTo('#productUnitList');
						$('#productUnitList').find('tr:last').find('.units').val(D[i].unit);
						if(!+D[i].unit_type){
							$('#productUnitList').find('tr:last').find('.rate').attr('disabled','disabled');
						}
						global_count++;
						checkSameUnit();
					}
				}
			}
		});
	};
	
	/**
	 * @desc 新增辅助单位
	 */
	$('#productUnitList').on('click','.add-unit',function(){
		insertOrginHtml();
		global_count++;
		
	})
	//删除数据
	$('#productUnitList').on('click','.stock-minus-tr',function(){
		var tmp_type = $(this).closest('td').next('td').attr('data-id');
		if(!+tmp_type){
			alertTips('warning','基本单位不能删除！');
			return false;
		}
		var tmp_id = $(this).closest('td').prev('td').attr('data-id');
		if ($.inArray(tmp_id, global_remove) >= 0) {
			return false;
		}
		if(tmp_id){
			global_remove.push({'product_unit_id':tmp_id});
		}
		if(global_count == 1){
			return false;
		} else if(global_count == 2){
			//添加一条数据要删除数据 后插入一条空数据
			$('#productUnitList').find('tr:first').remove();
			global_count--;
			insertOrginHtml();
			return false;
		} else {
			var self = $(this);
			//判断当前要删除的行,下面是否还有记录
            var nextTr = self.parent().parent().next('tr');
            if(nextTr.length){
            	//存在下一行，清空当前行数据
                self.closest('tr').remove();
                // 序号重新排列
                var td = $('#productUnitList').find('tr').find('td:first');
                $.each(td, function(index, item) {
                    var item = $(item);
                    item.text(index+1);
                })
                global_count--;
                return false;
            } else{
            	//删除的为最后一行
                self.closest('tr').remove();
                global_count--;
                return false;
            }
		}
		
	});
	
	var insertOrginHtml = function(){
		$('<tr>'
			+'<td class="text-center" name="ids" data-id="">'+global_count+'</td>'
			+'<td class="text-center"><a href="javascript:void(0)"class="stock-minus-tr" data-id=""> <i class="fa fa-minus-circle fa-lg" style="color: red;margin-top:10px;"></i></a></td>'
			+'<td class="text-center" name="unit_type" data-id="1">辅助单位</td>'
			+'<td class="text-center" name="name" data-id="" data-type="1">'+select_units
			+'<a class="add-btn add-unit" title="新增" style="float:left;margin:8px 10px 10px 10px;"'
			+'href="javascript:void(0)"><i class="fa fa-plus-circle fa-lg"></i></a></td>'
			+'<td class="text-center" name="rate"><input type="text" class="rate stock-input"></td>'
			+'<td class="text-center" name="format"><input type="text" class="format stock-input"></td>'
			+'<td class="text-center" name="remark"><input type="text" style="width:100%;" class="remark stock-input"></td>'
			+'</tr>').appendTo('#productUnitList');
	};
	
	function checkSameUnit(){
		$('#productUnitList').unbind('change').on('change','.units',function(){
			var unit = $(this).val();
			var unit_type = $(this).closest('td').attr('data-type');
			var _tr = $('#productUnitList').find('tr');
			var base_flag = 0;
			_tr.each(function(index,element){
				var tr = $(this);
				var unit_tmp = tr.find('[name="name"] select').val();
				var type = tr.find('[name="name"]').attr('data-type');
				
				if(unit_tmp == unit){
					base_flag++;
				}
			})
			if(base_flag > 1){
				alertTips('warning','重复的单位，请重新选择');
				$(this).val(0);
			}
			
		})
	};
	/**
	 * @var 保存辅助单位
	 */
	(function() {
		// 保存
		$('#save').on('click', function() {
			if(!+_id){
				alertTips('warning','请先保存商品信息！');
				return false;
			}
			//明细
			var detail = unit_detail();
			if(!detail){
				return false;
			}
			var ii = layer.load();
			$.post('save-product-unit',{'det':detail,'remove': global_remove,'pid':_id}, function(data,status){
				setTimeout(function(){
					  layer.close(ii);
				}, 1000);
				if(status =='success'){
					if(data.Ack =='Success'){
						alertTips('success','保存成功');
						setTimeout(function() {
							initProductUnit();
						}, 1000);
					}
				} else {
					alertShows('error','网络错误');
				}
			})
		});

	})();	
	
	$('#unit').change(function()
	{
		if ($(this).val() == 23) {
			$('#guide_price').css('width', '40%');
			$('.guide_price_jin').show();
		}
		else {
			$('#guide_price').css('width', '100%');
			$('.guide_price_jin').hide();
		}
	});
	$('#guide_price_jin').keyup(function()
	{
		var guide_price = Number($(this).val() * 2).toFixed(2);
		$('#guide_price').val(guide_price);
	});
	$('#guide_price').keyup(function()
	{
		var guide_price_jin = Number($(this).val() / 2).toFixed(2);
		$('#guide_price_jin').val(guide_price_jin);
	});

	//辅助单位列表
	var unit_detail = function(){
		var unit_det=[];
		global_det = [];
		var unit_info = [];
		var _tr = $('#productUnitList').find('tr');
		var flag = 1;
//		if(_tr.length == 1){
//			var pid = _tr.first('tr').find('td[name="name"]').attr('data-id');
//			if(pid == ''){
//				alertTips('warning','请选择商品');
//				return false;
//			}
//		}
		_tr.each(function(index,element){
			var tr = $(this);
			var unit = tr.find('[name="name"] select').val();
			if(!+unit){
				alertTips('warning','请选择单位');
				flag = 0;
				return false;
			}
			
			var rate = tr.find('[name="rate"] input').val();
			if(rate == ''){
				alertTips('warning','请填写比率');
				flag = 0;
				return false;
			}

			var line_id = tr.find('[name="ids"]').attr('data-id');
			if(line_id == ''){
				line_id = 0;
			}
			var unit_type = tr.find('[name="unit_type"] input').val();
			var format = tr.find('[name="format"] input').val();
			
			unit_det = {
				'product_unit_id' : line_id,
				'product_id' : _id,
				'unit_type' :tr.find('[name="unit_type"]').attr('data-id'), 
				'unit' : unit,
				'rate':rate,
				'format':format,
				'remark' : tr.find('[name="remark"] input').val(),
				
			};
			unit_info.push(unit_det);
			unit_det = [];
		});
		if(!flag){
			unit_info = [];
			return false;
		}
		if(unit_info.length == 0){
			alertTips('warning','请选择产品！');
			return false;
		}
		
		return unit_info;
	}
	
	//分拆商品
	/**
	 * @desc 选择商品
	 */
	$('#goodsList').on('click','.add-goods',function(){
		$('#productName').val('');
		getProducts();
		
	})
	//过滤商品
	$('#searchProduct').on('click', function() {
		var _name = trim($('#productName').val());
		global_product.name = _name;
		getProducts();
		return;
	})
	
	/**
	 * @desc 查询商品
	 */
	function getProducts(pageInfo){
		if (pageInfo !== undefined) {
			global_product.page = pageInfo.page;
			global_product.pageSize = pageInfo.pageSize;
		}
		$('#product_list').find('tr').remove();
		var index = layer.load();
		 $.ajax({
             url: '../instore/get-products',
             type: "GET",
             cache: true,
             data: global_product,
             dataType: "json",
             jsonp: "callback",
             global:false,
             success: function(data){
            	 layer.close(index);
            	 var P = data.Body.list;
					if(P && P.length){
						for(var i in P){
							var tmp_units = ''
								var U = P[i].product_unit;
								tmp_units = '<select class="form-control units"><option value="0" data-rate="0"> </option>';
								for(var j in U){
									tmp_units +='<option value="'+U[j].unit_id+'" data-rate="'+U[j].rate+'">'+U[j].unit_name+'</option>';
							}
							tmp_units +='</select>';
							$('<tr>'
							+'<td class="text-center">'+(+i+1)+'</td>'
							+'<td class="text-center id">'+P[i].product_id+'</td>'
							+'<td class="text-center name">'+P[i].product_name+'</td>'
							+'<td class="text-center sn">'+P[i].product_sn+'</td>'
//							+'<td class="text-center quantity">'+P[i].quantity+'</td>'
//							+'<td class="text-center price">'+P[i].price+'</td>'
							+'<td class="text-center unit" data-unit="'+P[i].quantity_unit+'" data-rela="'+P[i].unit_content+'">'+(P[i].unit_name == null ? '':P[i].unit_name)+'</td>'
							+'<td class="text-center"><a href="javascript:void(0)" class="product_select" data-unit="'+encodeURI(tmp_units)+'">选择</a></td>'
							+'</tr>').appendTo('#product_list');
			              
						}
						var pageInfo = data.Body.page;
			            if (typeof pageInfo !== 'undefined'){
			              	refreshPaginationNavBar2($('.paginationNavBar'), pageInfo.page, pageInfo.pageSize, data.Body.count, getProducts);
			            }
					}else {
						$('<tr><td colspan="5" class="text-center">没有数据</td></tr>').appendTo('#product_list');
						refreshPaginationNavBar2($('.paginationNavBar'), 1, 10, 1, getProducts);
					}
				$('#chooseProduct').modal('show');//选择商品窗口
             }
		 })
	}
	
	//添加商品
	$('#product_list').on('click','.product_select',function(){
		var tmp_units = decodeURI($(this).attr('data-unit'));
		var tr =$(this).closest('tr');
		var id = tr.find('.id').text();
		var name = tr.find('.name').text();
		
		if(goods_count == 1){
			var pid = $('#goodsList').find('.stock-minus-tr').attr('data-id');
			if(pid == undefined){
				//刚开始添加数据
				$('#goodsList').find('tr:first').remove();
			} ;
		}
		$('<tr>'
		  +'<td class="text-center" name="ids" data-id="">'+goods_count+'</td>'
		  +'<td class="text-center"><a href="javascript:void(0)"class="stock-minus-tr" data-id="'+id+'"> <i class="fa fa-minus-circle fa-lg" style="color:red;margin-top:10px;" ></i></a></td>'
		  +'<td class="text-center" name="goods_type" data-id="1">精拆商品</td>'
		  +'<td class="text-center" name="goods_id">'
		  +'<input title="商品ID" type="text" class="product-id stock-input50" disabled="" style="height: 30px;width:70%;float:left;" value="'+id+'">'
		  +'<a class="add-btn add-goods" title="新增" style="float:left;margin:8px 10px 10px 10px;"'
		  +'href="javascript:void(0)"><i class="fa fa-plus-circle fa-lg"></i></a></td>'
		  +'<td class="text-center" name="name" data-id="">'
		  +'<input title="商品名称" type="text" class="product-name stock-input50" value="'+name+'" disabled="" style="height: 30px;width:100%;float:left;"></td>'
//		  +'<<td class="text-center" name="remark"><input title="备注" type="text" class="remark stock-input" style="width: 100%;height:30px;"></td>'
		  +'</tr>').appendTo('#goodsList');
		goods_count++;
	})
	
	//删除数据
	$('#goodsList').on('click','.stock-minus-tr',function(){
		var tmp_type = $(this).closest('td').next('td').attr('data-id');
		if(!+tmp_type){
			alertTips('warning','原始商品不能删除！');
			return false;
		}
		var tmp_id = $(this).closest('td').prev('td').attr('data-id');
		if ($.inArray(tmp_id, product_remove) >= 0) {
			return false;
		}
		if(tmp_id){
			product_remove.push({'product_extend_id':tmp_id});
		}
		if(goods_count == 1){
			return false;
		} else if(goods_count == 2){
			//添加一条数据要删除数据 后插入一条空数据
			$('#goodsList').find('tr:first').remove();
			goods_count--;
			insertOrginHtml();
			return false;
		} else {
			var self = $(this);
			//判断当前要删除的行,下面是否还有记录
            var nextTr = self.parent().parent().next('tr');
            if(nextTr.length){
            	//存在下一行，清空当前行数据
                self.closest('tr').remove();
                // 序号重新排列
                var td = $('#goodsList').find('tr').find('td:first');
                $.each(td, function(index, item) {
                    var item = $(item);
                    item.text(index+1);
                })
                goods_count--;
                return false;
            } else{
            	//删除的为最后一行
                self.closest('tr').remove();
                goods_count--;
                return false;
            }
		}
		
	});
	
	/**
	 * @var 保存分拆商品
	 */
	(function() {
		// 保存
		$('#extend-save').on('click', function() {
			if(!+_id){
				alertTips('warning','请先保存商品信息！');
				return false;
			}
			//明细
			var detail = extend_detail();
			if(!detail){
				return false;
			}
			var ii = layer.load();
			$.post('save-product-extend',{'det':detail,'remove': product_remove,'pid':_id}, function(data,status){
				setTimeout(function(){
					  layer.close(ii);
				}, 1000);
				if(status =='success'){
					if(data.Ack =='Success'){
						alertTips('success','保存成功');
						setTimeout(function() {
							initProductExtend();
						}, 1000);
					}
				} else {
					alertShows('error','网络错误');
				}
			})
		});

	})();	
	
	
	//分拆列表
	var extend_detail = function(){
		var extend_det=[];
		var extend_info = [];
		var _tr = $('#goodsList').find('tr');
		var flag = 1;
		_tr.each(function(index,element){
			var tr = $(this);

			var line_id = tr.find('[name="ids"]').attr('data-id');
			if(line_id == ''){
				line_id = 0;
			}
			var goods_type = tr.find('[name="goods_type"]').attr('data-id');
			
			extend_det = {
				'product_extend_id' : line_id,
				'product_id' : tr.find('[name="goods_id"] input').val(),
				'goods_type' :goods_type, 
//				'name' : tr.find('[name="name"] input').val(),
				
			};
			extend_info.push(extend_det);
			extend_det = [];
		});
		if(!flag){
			extend_info = [];
			return false;
		}
		if(extend_info.length == 0){
			alertTips('warning','请选择产品！');
			return false;
		}
		return extend_info;
	}
	
	initProductExtend();
	/**
	 * @初始化页面
	 */
	function initProductExtend() {
		$.get('get-product-extend-info', {'id' : _id}, function(data, status) {
			if(status =='success' && data.Ack =='Success'){
				var D = data.Body;
				if(D){
					$('#goodsList').find('tr').remove();
					for(var i in D){
						$('<tr>'
							+'<td class="text-center" name="ids" data-id="'+D[i].product_extend_id+'">'+(+i+1)+'</td>'
							+'<td class="text-center"><a href="javascript:void(0)"class="stock-minus-tr" data-id=""> <i class="fa fa-minus-circle fa-lg" style="color: red;margin-top:10px;"></i></a></td>'
							+'<td class="text-center" name="unit_type" data-id="'+D[i].goods_type+'">'+(D[i].goods_type == 0?'原始商品':'精拆商品')+'</td>'
							+'<td class="text-center" name="goods_id">'
							+'<input title="商品ID" type="text" class="product-id stock-input50" disabled="" style="height: 30px;width:70%;float:left;" value="'+D[i].product_id+'">'
						    +'<a class="add-btn add-goods" title="新增" style="float:left;margin:8px 10px 10px 10px;"'
							+'href="javascript:void(0)"><i class="fa fa-plus-circle fa-lg"></i></a></td>'
							+'<td class="text-center" name="name" data-id="">'
							+'<input title="商品名称" type="text" class="product-name stock-input50" value="'+D[i].product_name+'" disabled="" style="height: 30px;width:100%;float:left;"></td>'
						   +'</tr>').appendTo('#goodsList');
						goods_count++;
					}
				}
			}
		});
	};
})